package main

import (
	"context"
	"flag"
	"fmt"
	code2 "goStudy/grpc/pubsub/code"
	pubsub "goStudy/grpc/pubsub/proto"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"io"
	"log"
	"net"
)

var (
	f string
	s string
)

func init()  {
	flag.StringVar(&f, "f", "", "")
	flag.StringVar(&s, "s", "", "")

}


func main()  {
	flag.Parse()

	switch f {
	case "server":
		server()
	case "sub":
		sub(s)
	case "pub":
		pub(s)

	}
}

func server()  {
	creds,err:=credentials.NewServerTLSFromFile("server.crt", "server.key")
	if err != nil {
		log.Fatal(err)
	}


	grpcServer := grpc.NewServer(grpc.Creds(creds),grpc.UnaryInterceptor(code2.ReqLog),grpc.StreamInterceptor(code2.ReqStreamLog))


	pubsub.RegisterPubsubServiceServer(grpcServer,code2.NewPubsubService())
	lis,err:=net.Listen("tcp",":1234")
	if err != nil {
		log.Fatal(err)
	}

	grpcServer.Serve(lis)
}

func sub(topic string)  {
	creds,err:=credentials.NewClientTLSFromFile("server.crt","server.grpc.io")
	if err != nil {
		log.Fatal(err)
	}

	conn,err:=grpc.Dial("localhost:1234",grpc.WithTransportCredentials(creds))
	if err != nil {
		log.Fatal(err)
	}

	client:=pubsub.NewPubsubServiceClient(conn)
	stream,err:=client.Subscribe(context.Background(),&pubsub.String{Value:topic})
	if err != nil {
		log.Fatal(err)
	}

	for {
		ack,err:=stream.Recv()
		if err != nil {
			if err == io.EOF {
				fmt.Println("服务器连接断开")
				break
			}
			log.Fatal(err)
		}

		fmt.Println("收到订阅消息:",ack.Value)

	}

}

func pub(content string)  {
	auth := &code2.Authentication{
		User:    "gopher",
		Password: "password",
	}

	creds,err:=credentials.NewClientTLSFromFile("server.crt","server.grpc.io")
	if err != nil {
		log.Fatal(err)
	}


	conn,err:=grpc.Dial("localhost:1234",grpc.WithTransportCredentials(creds),grpc.WithPerRPCCredentials(auth))
	if err != nil {
		log.Fatal(err)
	}

	client:=pubsub.NewPubsubServiceClient(conn)
	_,err=client.Publish(context.Background(),&pubsub.String{Value:content})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("消息已发布")

}